public class 两数相加 {

    private static Node numAdd(Node node1, Node node2){

        if(null == node1 || null == node2)  return null;

        Node resultNode = new Node(0);

        Node p, q, curr;
        p = node1;
        q = node2;
        curr = resultNode;

        int carry = 0;

        while (null!=p || null!=q) {
            

            int pVal = null!=p ? p.val : 0;
            int qVal = null!=q ? q.val : 0;

            int sum = pVal + qVal + carry;

            carry = sum / 10;

            curr.nextNode = new Node(sum % 10);

            curr = curr.nextNode;

            if(null!=p) p = p.nextNode;
            if(null!=q) q = q.nextNode;

        }


        if(carry > 0) curr.nextNode = new Node(carry);

        return resultNode.nextNode;


    }
   
    public static void main(String[] args) {
        
        Node node1 = new Node(2);
        node1.nextNode = new Node(4);
        node1.nextNode.nextNode = new Node(3);

        Node node2 = new Node(5);
        node2.nextNode = new Node(6);
        node2.nextNode.nextNode = new Node(4);

        Node result = numAdd(node1, node2);

        System.out.println(result.print());
    }

    private static class Node{

        private int val;
        private Node nextNode;

        public Node(int val){
            this.val = val;
        }

        public void setNextNode(Node nextNode){

            this.nextNode = nextNode;
        }


        public String print(){

            Node cur = this;

            StringBuilder builder = new StringBuilder();

            while (cur != null) {
                
                builder.append(cur.val);

                cur = cur.nextNode;

            }

            return builder.toString();

        }

    }
}
